package com.blb.blb_erp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.blb_erp.entity.SMenu;
import com.blb.blb_erp.mapper.SMenuMapper;
import com.blb.blb_erp.service.ISMenuService;
import com.blb.blb_erp.vo.TreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenheng
 * @since 2020-08-14
 */
@Service
public class SMenuServiceImpl extends ServiceImpl<SMenuMapper, SMenu> implements ISMenuService {

    @Autowired
    private SMenuMapper menuMapper;

    @Override
    public List<SMenu> findMenusByUserId(String userId) {
        //查询一级菜单
        List<SMenu> menus = menuMapper.selectMenusByPidAndUserId( userId,"0");
        //查询子菜单
        menus.forEach(menu -> {
            List<SMenu> sMenus = menuMapper.selectMenusByPidAndUserId(userId,menu.getId());
            menu.setSubMenus(sMenus);
        });
        return menus;
    }

    @Override
    public List<TreeVO> findMenuTrees() {
        //查询全部一级菜单以及子菜单
        List<SMenu> sMenus = menuMapper.selectMenusByPid("0");
        sMenus.forEach(menu -> {
            List<SMenu> sMenus1 = menuMapper.selectMenusByPid(menu.getId());
            menu.setSubMenus(sMenus1);
        });
        //将菜单转换为树节点
        List<TreeVO> treeVOS = new ArrayList<>();
        sMenus.forEach(menu ->{
            TreeVO treeVO = new TreeVO();
            treeVO.setId(menu.getId());
            treeVO.setLabel(menu.getMenuName());
            menu.getSubMenus().forEach(sMenu -> {
                TreeVO treeVO1 = new TreeVO();
                treeVO1.setId(sMenu.getId());
                treeVO1.setLabel(sMenu.getMenuName());
                treeVO.getChildren().add(treeVO1);
            });
            treeVOS.add(treeVO);
        });
        return treeVOS;
    }

    @Override
    public List<String> findMenuIdsByRoleId(String roleId) {
        List<SMenu> sMenus = menuMapper.selectMenusByRoleId(roleId);
        List<String> ids = new ArrayList<>();
        sMenus.forEach(menu -> {
            ids.add(menu.getId());
        });
        return ids;
    }
}
